<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择类型" clearable>
          <el-option v-for="dict in dict.type.file_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['filemgr:filemgr:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-sort" size="mini" @click="toggleExpandAll">展开/折叠</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-if="refreshTable" v-loading="loading" :data="filemgrList" row-key="id" :default-expand-all="isExpandAll"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
      <!-- <el-table-column label="ID" prop="id" width="55" /> -->
      <!-- <el-table-column label="ID" align="left" width="120" prop="id" /> -->
      <el-table-column label="类型" align="left" width="120" prop="type">
        <template slot-scope="scope">
          <span style="color: #409eff;">
            <i class="el-icon-folder-opened" v-if="scope.row.type == 1 && scope.treeNode.expanded" />
            <i class="el-icon-folder" v-else-if="scope.row.type == 1 && !scope.treeNode.expanded" />
            <i class="el-icon-document" style="color: red;" v-else></i>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="名称" prop="name" align="left">
        <template slot-scope="scope">
          <a style="color: #409eff" v-if="scope.row.type == 2" target="_blank" :href="api + scope.row.url">{{
            scope.row.name }}</a>
          <span v-else>{{ scope.row.name }}</span>
        </template></el-table-column>
      <el-table-column label="类型" align="center" prop="type" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.file_type" :value="scope.row.type" />
        </template>
      </el-table-column>
      <!-- <el-table-column label="地址" align="left" prop="url" /> -->
      <el-table-column label="分享" align="center" prop="share" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.share" :value="scope.row.share" />
        </template>
      </el-table-column>
      <el-table-column label="备注信息" align="center" prop="remark" width="120" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="220">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-share" @click="openShare(scope.row)"
            v-if="scope.row.share == 1 && scope.row.type == 2">分享</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['filemgr:filemgr:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-plus" @click="handleAdd(scope.row)"
            v-hasPermi="['filemgr:filemgr:add']">新增</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['filemgr:filemgr:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改文件对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="父文件" prop="pId">
          <treeselect v-model="form.pId" :options="filemgrOptions" :normalizer="normalizer" placeholder="请选择父文件" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio v-for="dict in dict.type.file_type" :key="dict.value" :label="dict.value">{{ dict.label
            }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="上传文件" prop="url" v-if="form.type == 2">
          <file-upload v-model="form.url" @fileName="fileName" :limit="1" />
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="分享" prop="share">
          <el-radio-group v-model="form.share">
            <el-radio v-for="dict in dict.type.share" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注信息" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="shareTitle" :visible.sync="shareOpen" width="800px" append-to-body>
      <el-form ref="shareForm" :model="shareForm" :rules="sharerules" label-width="120px">
        <el-form-item label="分享类型" prop="type">
          <el-radio-group v-model="shareForm.type">
            <el-radio v-for="dict in dict.type.share_type" :key="dict.value" :label="dict.value">{{ dict.label
            }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="分享给谁" prop="userId" v-if="shareForm.type == 2">
          <el-select v-model="shareForm.userId" placeholder="请选择分享的人">
            <el-option v-for="item in userList" :key="item.userId" :label="item.nickName"
              :value="item.userId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="时长类型" prop="timeType">
          <el-radio-group v-model="shareForm.timeType">
            <el-radio v-for="dict in dict.type.time_limit" :key="dict.value" :label="dict.value">{{ dict.label
            }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="时限" prop="deadline" v-if="shareForm.timeType == 2">
          <el-date-picker clearable v-model="shareForm.deadline" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择时限">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="审批人" prop="applyUserId">
          <el-select v-model="shareForm.applyUserId" placeholder="请选择分享的人">
            <el-option v-for="item in authUserList" :key="item.userId" :label="item.nickName"
              :value="item.userId"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitShare">确 定</el-button>
        <el-button @click="shareOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listFilemgr,
  getFilemgr,
  delFilemgr,
  addFilemgr,
  updateFilemgr,
} from "@/api/filemgr/filemgr";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {
  listUser
} from "@/api/system/user";
import {
  addSharemgr,
} from "@/api/filemgr/sharemgr";
import { allocatedUserList } from "@/api/system/role";
export default {
  name: "Filemgr",
  dicts: ["share", "file_type", 'share_type', 'time_limit'],
  components: {
    Treeselect,
  },
  data() {
    return {
      shareTitle: '',
      shareOpen: false,
      shareForm: {},
      sharerules: {
        deadline: [{ required: true, message: "时限不能为空", trigger: "blur" }],
        type: [{ required: true, message: "分享类型不能为空", trigger: "blur" }],
        timeType: [{ required: true, message: "时长类型不能为空", trigger: "blur" }],
        userId: [{ required: true, message: "分享谁不能为空", trigger: "blur" }],
        applyUserId: [{ required: true, message: "审批人不能为空", trigger: "blur" }],
      },
      shareRow: {},
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 文件表格数据
      filemgrList: [],
      // 文件树选项
      filemgrOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        name: null,
        url: null,
        share: null,
        type: null,
        pId: null,
        userId: null,
        userName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [{ required: true, message: "名称不能为空", trigger: "blur" }],
        url: [{ required: true, message: "地址不能为空", trigger: "blur" }],
        type: [{ required: true, message: "类型不能为空", trigger: "change" }],
        pId: [{ required: true, message: "父文件不能为空", trigger: "blur" }],
        share: [{ required: true, message: "分享不能为空", trigger: "blur" }],
      },
      api: process.env.VUE_APP_BASE_API,
      userList: [],
      authUserList: []
    };
  },
  created() {
    this.getList();
    this.getUser();
    this.getApplyUser();
  },
  methods: {
    getApplyUser() {
      allocatedUserList({
        pageNum: 1,
        pageSize: 1000000000,
        roleId: 6
      }).then(response => {
        this.authUserList = response.rows;
      }
      );
    },
    getUser() {
      listUser({
        pageNum: 1,
        pageSize: 1000000000,
      }).then(res => {
        this.userList = res.rows;
      })
    },
    openShare(row) {
      this.shareRow = row
      this.shareTitle = `分享：${row.name}`
      this.shareOpen = true
      this.shareForm = {
        fileId: row.id
      }
    },
    fileName(name) {
      this.form.name = name;
    },
    /** 查询文件列表 */
    getList() {
      this.loading = true;
      listFilemgr(this.queryParams).then((response) => {
        this.filemgrList = this.handleTree(response.data, "id", "pId");
        this.loading = false;
      });
    },
    /** 转换文件数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children,
      };
    },
    /** 查询文件下拉树结构 */
    getTreeselect() {
      listFilemgr().then((response) => {
        this.filemgrOptions = [];
        const data = { id: 0, name: "根目录", children: [] };
        data.children = this.handleTree(response.data, "id", "pId");
        this.filemgrOptions.push(data);
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        url: null,
        share: null,
        type: null,
        pId: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        userId: null,
        userName: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      this.getTreeselect();
      if (row != null && row.id) {
        this.form.pId = row.id;
      } else {
        this.form.pId = 0;
      }
      this.open = true;
      this.title = "添加文件";
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getTreeselect();
      if (row != null) {
        this.form.pId = row.pId;
      }
      getFilemgr(row.id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改文件";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateFilemgr(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addFilemgr(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal
        .confirm('是否确认删除文件编号为"' + row.id + '"的数据项？')
        .then(function () {
          return delFilemgr(row.id);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    submitShare() {
      this.$refs["shareForm"].validate((valid) => {
        if (valid) {
          addSharemgr({
            ...this.shareForm,
            status: 1
          }).then((response) => {
            this.$modal.msgSuccess("分享成功");
            this.shareOpen = false;
          });
        }
      });
    }
  },
};
</script>
